<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <el-input
          v-model="queryParams.roleKey"
          placeholder="请输入权限字符"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createTimeValue"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="btnSearch">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['system:role:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['system:role:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['system:role:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport()"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="fetchData"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableResult.rows" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色编号" prop="roleId" width="120" />
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="显示顺序" prop="roleSort" width="100" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">

          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            v-if="checkPermi(['system:role:edit'])"
            @change="handleStatusChange(scope.row)"
          ></el-switch>

          <dict-tag  v-else :options="dict.type.sys_normal_disable" :value="scope.row.status"></dict-tag>

        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:role:query']"
          >详情</el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:edit']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check"
                                v-hasPermi="['system:role:edit']">数据权限</el-dropdown-item>
              <el-dropdown-item command="handleAuthUser" icon="el-icon-user"
                                v-hasPermi="['system:role:edit']">分配用户</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="tableResult.total>0"
      :total="tableResult.total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="fetchData"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :before-close="cancelForm" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
         <span slot="label">
           <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
             <i class="el-icon-question"></i>
           </el-tooltip>
           权限字符
         </span>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 显示详情-->
    <el-dialog title="详情" :visible.sync="openDetail" width="800px" append-to-body>
      <el-form ref="form" :model="formDetail"  label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          {{formDetail.roleName}}
        </el-form-item>
        <el-form-item label="角色名称"  prop="roleKey">
          {{formDetail.roleKey}}
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          {{formDetail.roleSort}}
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formDetail.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menuDetail')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menuDetail')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menuDetail')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menuDetail"
            node-key="id"
            :check-strictly="!formDetail.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openDetail=false">取 消</el-button>
      </div>

    </el-dialog>


  </div>
</template>

<script>
import { listRole ,addAPI,updateRole, delRole, getRole,checkRoleNameUnique, checkRoleKeyUnique, changeRoleStatus} from "@/api/system/role"
import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu"
import PageMixin from '@/mixins/PageMixin.js'
import AddOrEditMixin from '@/mixins/AddOrEditMixin.js'

export default {
  name: "Role",
  mixins: [PageMixin, AddOrEditMixin],
  // 初始化加载 sys_dict_data表中dict_type=赋值的数据,相当于混入编程
  dicts: ['sys_normal_disable'],
  data() {


    // 检查角色名称是否被占用
    var roleNameCheckUsed = (rule, value, callback) => {
      const params = { id: this.form[this.primaryKey], value: value }

      checkRoleNameUnique(params).then(resp => {
        // 被使用了
        if (resp.data) {
          callback(new Error(resp.data))
        } else {
          callback()
        }
      })
    }

    // 检查角色key是否被占用
    var roleKeyCheckUsed = (rule, value, callback) => {
      const params = { id: this.form[this.primaryKey], value: value }

      checkRoleKeyUnique(params).then(resp => {
        // 被使用了
        if (resp.data) {
          callback(new Error(resp.data))
        } else {
          callback()
        }
      })
    }

    return {
      //新增API
      addApi: addAPI,
      // 修改API
      editApi: updateRole,
      // 删除API,
      delApi: delRole,
      // 所有菜单列表
      menuOptions: [],
      // 菜单全部折叠
      menuExpand: false,
      // 菜单全选
      menuNodeAll: false,
      // 菜单列表属性
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "不能为空", trigger: "blur" },
          { validator: roleNameCheckUsed, trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: "不能为空", trigger: "blur" },
          { validator: roleKeyCheckUsed, trigger: 'blur' }
        ],
        roleSort: [
          { required: true, message: "不能为空", trigger: "blur" }
        ]
      }

    }
  },
  created() {
    this.initFormValue()
  },
  methods: {
    /** 查询角色列表 */
    fetchDataHook() {
      return listRole
    },
    handleStatusChange(row) {

      // 超级管理员任何人都不能更改
      if(row[this.primaryKey]==1){
        row.status = '0'
        return
      }

      this.$confirm('确定更改状态吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        changeRoleStatus(row[this.primaryKey], row.status ) .then(resp => {
          // 重新查询数据
          this.fetchData()
        }).catch(e=> {
          row.status = row.status==='1'? '0' : '1'
        })

      }).catch(() => {
        // 取消
        row.status = row.status==='1'? '0' : '1'
      })

    },
    // 更多操作触发
    handleCommand(command, row) {

    },
    // 导出excel
    handleExport(){
      this.download('/api/system/role/export', this.queryParams,'角色数据.xlsx')
    },
    // 全选/全不选
    handleCheckedTreeNodeAll(value, type){
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      }else if(type ==='menuDetail'){
        this.$refs.menuDetail.setCheckedNodes(value ? this.menuOptions: []);
      }
    },
    handleCheckedTreeConnect(value, type){
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false
      }else if(type ==='menuDetail'){
        this.formDetail.menuCheckStrictly = value ? true: false
      }
    },
    // 展开/折叠
    handleCheckedTreeExpand(value, type){
      console.log(value)
      console.log(type)
      // 菜单的展开/折叠
      if(type === 'menu'){
        for(let i=0;i<this.$refs.menu.store._getAllNodes().length;i++){
          this.$refs.menu.store._getAllNodes()[i].expanded = value
        }
      }else if(type === 'menuDetail'){
        for(let i=0;i<this.$refs.menuDetail.store._getAllNodes().length;i++){
          this.$refs.menuDetail.store._getAllNodes()[i].expanded = value
        }
      }
    },
    /** 点击新增的时候,查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(resp => {
        this.menuOptions = resp.data;
      });
    },
    // 初始化新增和修改表单的值
    initFormValue() {
      // 实体类主键属性
      this.primaryKey= 'roleId'
      // 清空所有菜单选择
      if (this.$refs.menu) {
        this.$refs.menu.setCheckedKeys([])
      }
      // 折叠
      this.menuExpand = false
      // 全部不要选中
      this.menuNodeAll = false

      this.form ={
        roleSort: 0,
        status: "0",
        menuIds: [],
        deptIds: [],
        menuCheckStrictly: true,
        deptCheckStrictly: true
      }

    },
    // 点击新增按钮的要做的事情
    preAddHandler(){
      this.getMenuTreeselect()
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      //合并两个数组
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 新增保存之前的操作
    preAddSaveHandler(){
      this.form.menuIds = this.getMenuAllCheckedKeys()
    },
    // 根据id查询
    fetchByIdHook() {
      return getRole
    },
    // 点击修改按钮要做的事情
    preEditHandler(id){
      // 查询该角色的菜单权限
      const roleMenuResponse = this.getRoleMenuTreeselect(id)
      //循环遍历拥有的角色，并且赋值给前端
      this.$nextTick(() => {
        roleMenuResponse.then(res => {
          let checkedKeys = res.data.checkedKeys
          checkedKeys.forEach((v) => {
            this.$nextTick(()=>{
              this.$refs.menu.setChecked(v, true ,false);
            })
          })

        })
      })

    },
    // 点击详情按钮之前做的事情
    preViewHandler(id){
      // 查询该角色的菜单权限
      const roleMenuResponse = this.getRoleMenuTreeselect(id)
      //循环遍历拥有的角色，并且赋值给前端
      this.$nextTick(() => {
        roleMenuResponse.then(res => {
          let checkedKeys = res.data.checkedKeys
          checkedKeys.forEach((v) => {
            this.$nextTick(()=>{
              this.$refs.menuDetail.setChecked(v, true ,false);
            })
          })

        })
      })
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then( resp => {
        this.menuOptions = resp.data.menus
        return resp
      })
    },
    // 修改保存之前要做的事情
    preEditSaveHandler(){
      this.form.menuIds = this.getMenuAllCheckedKeys()
    }
  }

}
</script>
